﻿#include "MesQueryOpr.h"
#include <QUuid>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <memory>
#include "restclient-cpp/connection.h"
#include <utils.h>


MesQueryOpr::MesQueryOpr()
{
	initSmtInputVariables();
	initSmtOutPutVariables();
	initSmtSettingPages();
	initSmtRoiPageSetting();
}

MesQueryOpr::~MesQueryOpr()
{
}

long MesQueryOpr::run()
{
	SMTVariant tmpVariant;
	// 插件执行次数加1
	int execCount = 0;
	m_paraOutput[3].getValue(&tmpVariant);
	tmpVariant.toInt(&execCount);
	execCount += 1;
	m_paraOutput[3].setValue(execCount);
	
	// 把数据从链表中取出
	SMTString mesUrl;
	m_paraInput[0].getValue(&tmpVariant);
	tmpVariant.toString(&mesUrl);
	int tableNum;
	m_paraInput[1].getValue(&tmpVariant);
	tmpVariant.toInt(&tableNum);
	SMTString smtBarCode;
	m_paraInput[2].getValue(&tmpVariant);
	tmpVariant.toString(&smtBarCode);

	// 组装请求数据
	QJsonObject jsonObj;
	QJsonDocument jsonDoc;
	jsonObj.insert("BARCODE", smtBarCode.toLocal8Bit().constData());
	jsonObj.insert("TABLE_NUM", tableNum);
	jsonDoc.setObject(jsonObj);
	QByteArray qByteArray = jsonDoc.toJson(QJsonDocument::Compact);

	// 发送查询请求
	QString token = "abc123";
	std::string contentType = "application/json";
	std::unique_ptr<RestClient::Connection> conn = std::make_unique<RestClient::Connection>(mesUrl.toLocal8Bit().constData());
	conn->AppendHeader("Content-Type", contentType);
	// 添加请求头
	conn->AppendHeader("Authorization", token.toLocal8Bit().constData());
	conn->SetTimeout(3);

	DWORD startTime = GetTickCount();
	RestClient::Response response = conn->post("", qByteArray.constData());
	DWORD endTime = GetTickCount();
	DWORD httpTimeCost = endTime - startTime;
	// 设置结果到输出变量
	int retCode = response.code;
	m_paraOutput[0].setValue(retCode);
	m_paraOutput[1].setValue(response.body.c_str());
	m_paraOutput[2].setValue((long)httpTimeCost);
	// 查询MES次数加1
	int mesQueryCount = 0;
	m_paraOutput[4].getValue(&tmpVariant);
	tmpVariant.toInt(&mesQueryCount);
	mesQueryCount += 1;
	m_paraOutput[4].setValue(mesQueryCount);

	// 解析结果
	if (!(retCode == 200 || retCode == 0))
	{
		return -1;
	}
	// 解析响应Json
	QString body = QString::fromLocal8Bit(response.body.c_str());
	QJsonDocument responseJson = QJsonDocument::fromJson(body.toLocal8Bit().constData());
	QJsonObject bodyObj = responseJson.object();
	m_paraOutput[5].setValue(bodyObj.value("ErrorCode").toString().toInt());
	m_paraOutput[6].setValue(bodyObj.value("Message").toString().toLocal8Bit().constData());
	QJsonObject dataObj = bodyObj.value("Data").toArray()[0].toObject();
	m_paraOutput[7].setValue(dataObj.value("MODEL_NAME").toString().toLocal8Bit().constData());

	return 0;
}



int MesQueryOpr::SettingPageCount()
{
	return 1;
}

SMTSettingPage* MesQueryOpr::createSettingPage(int index)
{
	if (index == 0)
	{
		SMTSettingPage* page = new MesQuerySettingPage();
		page->setOperator(this);
		return page;
	}
	else
	{
		return nullptr;
	}
}

void MesQueryOpr::initSmtOutPutVariables()
{
	// 0
	SMTVariable httpCode(SMTVariable::VARIABLE_NUMBER,
		QStringLiteral("HttpCode").toLocal8Bit().constData(),
		QStringLiteral("Http Code. Mes系统响应状态码").toLocal8Bit().constData(), this);
	m_paraOutput.push_back(httpCode);
	// 1
	SMTVariable httpRsp(SMTVariable::VARIABLE_STRING,
		QStringLiteral("HttpRsp").toLocal8Bit().constData(),
		QStringLiteral("Http Rsp. Mes系统响应报文").toLocal8Bit().constData(), this);
	m_paraOutput.push_back(httpRsp);
	// 2
	SMTVariable httpTimeCost(SMTVariable::VARIABLE_NUMBER,
		QStringLiteral("HttpTimeCost").toLocal8Bit().constData(),
		QStringLiteral("Http Time Cost. 查询Mes系统请求耗时,单位ms").toLocal8Bit().constData(), this);
	m_paraOutput.push_back(httpTimeCost);
	// 3
	SMTVariable executionCount(SMTVariable::VARIABLE_NUMBER,
		QStringLiteral("ExecutionCount").toLocal8Bit().constData(),
		QStringLiteral("Execution Count. 自第一次配置以来插件执行次数").toLocal8Bit().constData(), this);
	m_paraOutput.push_back(executionCount);
	// 4
	SMTVariable mesQueryCount(SMTVariable::VARIABLE_NUMBER,
		QStringLiteral("MesQueryCount").toLocal8Bit().constData(),
		QStringLiteral("Mes Query Count. 自第一次配置以来查询Mes系统次数").toLocal8Bit().constData(), this);
	m_paraOutput.push_back(mesQueryCount);

	// 5
	SMTVariable errorCode(SMTVariable::VARIABLE_NUMBER,
		QStringLiteral("ErrorCode").toLocal8Bit().constData(),
		QStringLiteral("Error Code. Mes系统返回的错误码").toLocal8Bit().constData(), this);
	m_paraOutput.push_back(errorCode);
	// 6
	SMTVariable errorMsg(SMTVariable::VARIABLE_STRING,
		QStringLiteral("ErrorMsg").toLocal8Bit().constData(),
		QStringLiteral("Error Msg. Mes系统返回的错误信息").toLocal8Bit().constData(), this);
	m_paraOutput.push_back(errorMsg);
	// 7
	SMTVariable productModel(SMTVariable::VARIABLE_STRING,
		QStringLiteral("ProductModel").toLocal8Bit().constData(),
		QStringLiteral("Product Model. Mes查询到的产品型号").toLocal8Bit().constData(), this);
	m_paraOutput.push_back(productModel);
}

void MesQueryOpr::initSmtInputVariables()
{
	// 0
	SMTVariable url(SMTVariable::VARIABLE_STRING,
		QStringLiteral("MesQueryURL").toLocal8Bit().constData(),
		QStringLiteral("Query URL of Mes. Mes系统查询URL地址").toLocal8Bit().constData(), this);
	m_paraInput.push_back(url);
	// 1
	SMTVariable tableNum(SMTVariable::VARIABLE_NUMBER,
		QStringLiteral("TableNum").toLocal8Bit().constData(),
		QStringLiteral("Table Num. 工位编号").toLocal8Bit().constData(), this);
	m_paraInput.push_back(tableNum);
	// 2
	SMTVariable barCode(SMTVariable::VARIABLE_STRING,
		QStringLiteral("BarCode").toLocal8Bit().constData(),
		QStringLiteral("BarCode. 条码信息").toLocal8Bit().constData(), this);
	m_paraInput.push_back(barCode);
}

void MesQueryOpr::initSmtOprProperties()
{
	m_name = "MesQueryOpr";
	m_ID = QUuid::createUuid().toString().toLocal8Bit().constData();
}

void MesQueryOpr::initSmtSettingPages()
{
	//设置不需要的通用界面
	m_sorter.setEnabled(false);
	m_filter.setEnabled(false);

	//设置需要的通用界面
	m_preprocessor.setEnabled(false);
	m_graphics.setEnabled(true);
	m_outputValidator.setEnabled(true);
	m_roi.setEnabled(false);
}

void MesQueryOpr::initSmtRoiPageSetting()
{
}


// 创建算子插件，必须
SMTOperator *createOperator()
{
	return new MesQueryOpr();
}

// 释放算子插件，必须
void releaseOperator(SMTOperator *opr)
{
	MesQueryOpr *op = dynamic_cast<MesQueryOpr *>(opr);
	if (op != nullptr)
	{
		delete op;
	}
	return;
}

